import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components'
import Iconfont from '@/components/Iconfont'
import { staticUrl } from '@/utils'
import classnames from 'classnames'
import { AtIcon } from 'taro-ui'
import { getOrderList, getTypeConfig, cancelOrder, cancelBooking } from '@/api/order'
import dayjs from 'dayjs'
import './index.scss'
const bubbleImg = 'https://static3.jekunauto.com/img/others/bubble.png'

const arrawIcon = staticUrl('/img/order/arraw.png')
const goodIcon = staticUrl('/img/order/icon-good.png')
const goodIcon1 = staticUrl('/img/order/icon-good1.png')
const couponIcon = staticUrl('/img/order/icon-coupon.png')
const couponIcon1 = staticUrl('/img/order/icon-coupon1.png')
const chexianIcon = staticUrl('/img/order/icon-chexian.png')
const chexianIcon1 = staticUrl('/img/order/icon-chexian1.png')
const commerceLogo = staticUrl('/img/order/commerce-logo.png')
const forceLogo = staticUrl('/img/order/force-logo.png')
const allIcon = staticUrl('/img/order/icon-all.png')
const allIcon1 = staticUrl('/img/order/icon-all1.png')
const iconAccident = staticUrl('/img/order/icon-accident.png')
const iconAccident1 = staticUrl('/img/order/icon-accident1.png')

interface State {
  showType: boolean
  typeList: any
  currentType: number
  list: any
  tabStatus: number | string
  isBack: boolean
	isShowToggle: boolean
}
export default class Index extends Component {
  $instance = getCurrentInstance();

  constructor (props) {
    super(props)
    this.state = {
      showType: false,
      typeList: [],
      currentType: 0,
      list: [],
      tabStatus: '',
      isBack: false,
			isShowToggle:false
    }
  }

  state: State

  UNSAFE_componentWillMount() { }
  componentDidMount() {
    const { refund } = this.$instance.router.params
    if (refund) {
      this.getOrderList()
      Taro.setNavigationBarTitle({
        title: '退款/售后'
      })
    } else {
      this.getTypeConfig()
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    if (this.state.isBack) {
      const { refund } = this.$instance.router.params
      if (refund) {
        this.getOrderList()
      } else {
        this.getTypeConfig()
      }
    }
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }
	handleToggle(event){
		event.stopPropagation()
		let {isShowToggle} = this.state
		this.setState({
			isShowToggle:!isShowToggle
		})
	}
  // 获取分类配置
  getTypeConfig() {
    getTypeConfig().then(res => {
      const data = res.data.data
      const { tabStatus } = this.state
      let paramsTabStatus: number | string = this.$instance.router.params.tabStatus
      let paramsType: number | string = this.$instance.router.params.type
      if (paramsTabStatus) {
        if (/\d/.test(paramsTabStatus)) {
          paramsTabStatus = Number(paramsTabStatus)
        }
      } else {
        paramsTabStatus = tabStatus
      }
      let newState: any = {
        typeList: data,
        tabStatus: paramsTabStatus
      }
      if (paramsType) {
        const curTypeIndex = data.findIndex(v => v.type === Number(paramsType))
        Taro.setNavigationBarTitle({
          title: data[curTypeIndex].label
        })
        newState.currentType = curTypeIndex
      }
      this.setState(newState, () => this.getOrderList())
    })
  }
  private PER_PAGE: number = 6
  private MAX_PAGE: number = 1
  private currPage: number = 1
  private orderLoaded: boolean = false
  private isPageEnd: boolean = false
  // 获取订单列表
  getOrderList(mode: string = 'init') {
    if (this.orderLoaded) return
    this.orderLoaded = true
    if (mode === 'init') {
      this.currPage = 1
      this.isPageEnd = false
    } else {
      this.currPage++
      this.isPageEnd = this.currPage > this.MAX_PAGE
      // console.log(this.currPage > this.MAX_PAGE, this.currPage, this.MAX_PAGE)
      this.orderLoaded = false
    }
    if (this.isPageEnd) return
    const { currentType, tabStatus, typeList } = this.state
    const currPage = this.currPage
    let params: any = {}

    const { refund } = this.$instance.router.params
    if (refund) {
      params.query = {
        page: currPage,
        filter: {
          and: [{
            businessStatus: { in: [6, 7] }
          }]
        },
        perPage: this.PER_PAGE
      }
    } else {
      const isNumber = str => /\d/.test(String(str))
      const filterStatus = isNumber(tabStatus) && { businessStatus: tabStatus }
      const typeStatus = isNumber(typeList[currentType].type) && { type: typeList[currentType].type }
      const filterAnd: any = []
      if (filterStatus) {
        filterAnd.push(filterStatus)
      }
      if (typeStatus) {
        filterAnd.push(typeStatus)
      }
      params.query = {
        page: currPage,
        filter: {
          and: [...filterAnd]
        },
        perPage: this.PER_PAGE,
        from_order_number: null
      }
    }
    Taro.showLoading({ title: '加载中' })
    getOrderList(params).then(res => {
      const data = res.data.data
      this.orderLoaded = false
      Taro.hideLoading()
      if (mode === 'init') {
        this.MAX_PAGE = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
        this.setState({
          list: data
        })
      } else {
        const { list } = this.state
        this.setState({
          list: [...list, ...data]
        })
      }
    }).catch(e => {
      this.orderLoaded = false
      Taro.hideLoading()
    })
  }

  // 滚动加载
  scrollLoad(e) {
    // console.log(e)
    this.getOrderList('add')
  }

  // 切换分类
  changeType(index: number | string) {
    const { typeList, currentType } = this.state
    console.log(currentType, index)
    if (currentType === index) return
    this.setState({
      currentType: index,
      tabStatus: '',
      showType: false
    }, () => {
      Taro.setNavigationBarTitle({
        title: typeList[index].label
      })
      Taro.pageScrollTo({
        scrollTop: 0
      })
      this.getOrderList()
    })
  }

  // 切换类型
  changeTabStatus(index: number | string) {
    const { tabStatus } = this.state
    if (tabStatus === index) return
    this.setState({
      tabStatus: index,
      showType: false
    }, () => {
      Taro.pageScrollTo({
        scrollTop: 0
      })
      this.getOrderList()
    })
  }
  // 跳转到订单详情
  linkToDetail({ orderNumber, type, insurance, accidentInsurance }) {
    /*type
    商品订单：0
    年卡订单：1
    方案确认单：2
    定金单：3
    零售单：4
    保险单：5
    e保养： 16
    e保养+： 17
    e轮胎： 18
    e轮胎+： 19
    e保养+： 20
    */
    if (type === 13) { // 驾驭险
      const path: string = '/insurance/driving/order-detail'
      const query: any = {
        id: accidentInsurance.id
      }
      Taro.navigateTo({ url: `/pages/webview/index/index?path=${path}&query=${JSON.stringify(query)}` })
      // https://test-fn-m.jekunauto.com/#/insurance/driving/order-detail?id={id}
    } else if (type === 5) {
      // 保险订单
      // console.log('insurance', insurance)
      const path: string = '/insurance/order-detail'
      const query: any = {
        id: insurance.id
      }
      Taro.navigateTo({ url: `/pages/webview/index/index?path=${path}&query=${JSON.stringify(query)}` })
    } else {
      Taro.navigateTo({ url: `/pages/order/details/index?orderNumber=${orderNumber}&type=${type}` })
    }
  }
  // 去支付
  toPay(orderNumber) {
    Taro.navigateTo({
      url: '/pages/order/pay/index?orderNumber=' + orderNumber
    })
  }
  // 预约时间
  bookingOrder(details, mode?) {
    this.setState({
      isBack: true
    }, () => {
      let goods = []
      if (details.items) {
        goods = details.items.goods.map(v => {
          const { goodsId, goodsSkuId, number, type } = v
          return {
            goodsId,
            goodsSkuId,
            number,
            type
          }
        })
      }
      if (mode === 'edit') {
        Taro.navigateTo({ url: `/pages/order/booking/index?orderNumber=${details.orderNumber}&order=${JSON.stringify(goods)}&applyTime=${details.apply.time}` })
      } else {
        Taro.navigateTo({ url: `/pages/order/booking/index?orderNumber=${details.orderNumber}&order=${JSON.stringify(goods)}` })
      }
    })
  }
  // 取消订单
  cancelOrder(orderNumber) {
    Taro.showModal({
      title: '取消订单',
      content: '确定取消订单吗？',
      success: async (res) => {
        try {
          if (res.confirm) {
            await cancelOrder({ orderNumber })
            this.getOrderList()
            Taro.showToast({
              icon: 'none',
              title: '取消订单成功'
            })
          }
        } catch (e) {
          Taro.showToast({
            icon: 'none',
            title: '接口异常'
          })
        }
      }
    })
  }

  // 取消预约
  cancelApply(orderNumber) {
    Taro.showModal({
      title: '取消预约',
      content: '确定取消预约吗？',
      success: async (res) => {
        try {
          if (res.confirm) {
            await cancelBooking({ orderNumber })
            this.getOrderList()
            Taro.showToast({
              icon: 'none',
              title: '取消预约成功'
            })
          }
        } catch (e) {
          Taro.showToast({
            icon: 'none',
            title: '接口异常'
          })
        }
      }
    })
  }


  render() {
    const { showType, typeList, currentType, tabStatus, list,isShowToggle } = this.state
    const tabList = (typeList && typeList.length) ? typeList[currentType].items : []
    // console.log(/\d/.test(tabStatus))
    const { refund } = this.$instance.router.params
    return (
      <ScrollView scrollY lowerThreshold={150} onScrollToLower={(e) => this.scrollLoad(e)} className={classnames('order-list', refund && 'hide-menu')}>
        <View className={classnames('order-menu')}>
          <View className='btn-group'>
            {/* <View className='btn' onClick={() => this.changeTabStatus(-1)}><Text className={classnames('text', tabStatus === -1 && 'curr')}>全部</Text></View> */}
            {
              tabList.map(v => {
                return <View onClick={() => this.changeTabStatus(v.status)} key={v.status} className='btn'><Text className={classnames('text', {
                  'curr': tabStatus === v.status
                })}
                >{v.label}</Text></View>
              })
            }
          </View>
          <View className='tab-order-type' onClick={() => this.setState({ showType: true })} >
            <Image lazyLoad className='pic' src={arrawIcon} />
            <Iconfont size='26' color='#ccc' name='icon-shaixuanxialajiantou' />
          </View>
        </View>

        <View onTouchMove={(e) => e.preventDefault()} className={classnames('select-type-container', showType && 'show')}>
          <View className='mask' onClick={() => this.setState({ showType: false })}></View>
          <View className='select-type'>
            {
              typeList.map((v, index) => {
                let imgUrl = ''
                if (v.type === '') {
                  imgUrl = currentType === index ? allIcon1 : allIcon
                }
                if (v.type === 0) {
                  imgUrl = currentType === index ? goodIcon1 : goodIcon
                }
                if (v.type === 1) {
                  imgUrl = currentType === index ? couponIcon1 : couponIcon
                }
                if (v.type === 5) {
                  imgUrl = currentType === index ? chexianIcon1 : chexianIcon
                }
                if (v.type === 13) {
                  imgUrl = currentType === index ? iconAccident1 : iconAccident
                }
                return (
                  <View key={v.value} onClick={() => this.changeType(index)} className={classnames('btn', currentType === index && 'active')} >
                    {imgUrl && <Image lazyLoad className='pic' src={imgUrl} />}
                    {v.label}
                  </View>
                )
              })
            }
          </View>
        </View>
        <View className='order-wrap'>
          {
            list && list.map(v => {
              let hasGoods = v.items && (Object.keys(v.items).length && v.items.goods)
              const goods = hasGoods ? v.items.goods > 4 ? v.items.goods.slice(0, 4) : v.items.goods : []
              const hasAction = Object.keys(v.action).every(key => v.action[key] == 0)
              let totalGoodsNumber = 0
              let programmeNumber = 0 //方案单商品数量
              if (hasGoods) {
                v.items.goods.forEach(gds => {
                  totalGoodsNumber += Number(gds.number)
                })
              }
              // 方案单商品数量
              if (v.type === 4 || v.type === 2 && v.items.sku && v.items.sku.length > 0) {
                v.items.sku.forEach(val => {
                  programmeNumber += Number(val.number)
                })
              }
              if (v.type === 5) {
                totalGoodsNumber = +v.insurance.isHaveCommerce + +v.insurance.isHaveForce
              }
              if (v.type === 20) {
                v.items.sku.forEach(val => {
                  totalGoodsNumber += Number(val.number)
                })
              }
              if ([16, 17, 18, 19].includes(+v.type)) {
                v.items.goods.forEach(val => {
                  totalGoodsNumber += Number(val.number)
                })
              }
              return (
                <View key={v.id} className='order-card'>
									{
										v.type == 1 ?
										<View className='order-card-nk-box' onClick={() => this.linkToDetail(v)}>
											<View className='order-card-hd'>
												<View className='title title-esp'>{ v.orderNumber}</View>
												<View className={classnames('text', {
											'gery': v.businessStatus === 3
										})}>{v.businessStatusLabel}</View>
											</View>
											<View className='nk-info'>
											<View className='nk-name'>{v.annualCardItem.annualCardName}</View>
											<View className='nk-extra'>
												<Text className='nk-type'>{v.annualCardItem.annualCardTypeLabel}</Text>
												{
													v.annualCardItem.startDate !=='' ? <Text className='nk-date' >有效日期：{v.annualCardItem.startDate} ~ {v.annualCardItem.endDate}</Text> : null
												}

											</View>
										</View>
                  </View>
									 : <View className='order-card-hd' onClick={() => this.linkToDetail(v)}>
                    <View className='title'>{v.type == 13 ? v.storeName : v.orderNumber}</View>
                    <View className={classnames('text', {
											'gery': v.businessStatus === 3
										})} >{v.businessStatusLabel}</View>
                  </View>
									}


                  <View className='order-card-bd' onClick={() => this.linkToDetail(v)}>
										{/* 年卡特殊处理 */}

										{
											v.type === 1 && v.annualCardItem.itemList && v.annualCardItem.itemList.length && <View className='nk-list-box'>

												<View className='nk-list-inner'>
													{
														v.annualCardItem.showType === 1 ? <View className='nk-list-header'>
														<Text>项目</Text>
														<View>
															<Text className='c1'>{v.annualCardItem.label.split('/')[0]}</Text>
															<Text className='c2'>/{v.annualCardItem.label.split('/')[1]}</Text>
														</View>
													</View> : null
													}


											{
													v.annualCardItem.itemList.map((list)=>{
														return <View className='nk-list-header'>
														<Text className='c2'>{list.goodsName}</Text>
														{
															v.annualCardItem.showType === 0 ? <View>
															<Text className='c2'>x{list.number}</Text>
														</View> : <View>
															<Text className='c1'>{list.remainNum}</Text>
															<Text className='c2'>/{list.useNum}</Text>
														</View>
														}

													</View>
													})
												}

												</View>
												{
													isShowToggle && v.annualCardItem.giftList && v.annualCardItem.giftList.length ? <View className='nk-list-inner' >
													<View className='nk-list-header'>
														<Text>赠品</Text>
														{
															v.annualCardItem.showType !== 0 ? <View>
															<Text className='c1'>{v.annualCardItem.label.split('/')[0]}</Text>
															<Text className='c2'>/{v.annualCardItem.label.split('/')[1]}</Text>
														</View> : null
														}
													</View>
													{
													v.annualCardItem.giftList && v.annualCardItem.giftList.length && v.annualCardItem.giftList.map((list)=>{
														return <View className='nk-list-header'>
														<Text className='c2'>{list.goodsName}</Text>
														{
															v.annualCardItem.showType === 0 ? <View>
															<Text className='c2'>x{list.number}</Text>
														</View> : <View>
															<Text className='c1'>{list.type === 1 ? '￥': ''}{list.remainNum}</Text>
															<Text className='c2'>/{list.type === 1 ? '￥': ''}{list.useNum}</Text>
														</View>
														}

													</View>
													}) || null
												}
												</View> : null
												}

												{
													v.annualCardItem.giftList && v.annualCardItem.giftList.length ? <View className='nk-toggle' onClick={(event)=>this.handleToggle(event)}>
													<Text className='txt'>{!isShowToggle ? '展开' : '收起'}</Text>
													{
														!isShowToggle ? <AtIcon  value='chevron-down' className='toggle-ico' size='20' color='#999'></AtIcon> : <AtIcon  value='chevron-up' className='toggle-ico' size='20' color='#999'></AtIcon>
													}
												</View> : null
												}

											</View>
										}


                    {
                      v.type === 5 && <View className='order-goods-items'>
                        {
                          v.insurance && v.insurance.isHaveCommerce && <View className='goods-img'>
                            <Image lazyLoad className='pic' src={commerceLogo} />
                          </View>
                        }
                        {
                          v.insurance && v.insurance.isHaveForce && <View className='goods-img'>
                            <Image lazyLoad className='pic' src={forceLogo} />
                          </View>
                        }
                      </View>
                    }
                    {
                      hasGoods && goods.length === 1 && v.type !== 1 ? goods.map(good => {
                        return (
                          <View key={good.goodsId} className='order-goods-items'>
                            <View className='goods-img'>
                              <Image lazyLoad className='pic' src={good.goodsThumbnail} />
                            </View>
                            <View className='goods-info'>
                              <View className='name'>{good.goodsName}</View>
                              <View className='sku'>{good.goodsSkuName}</View>
                            </View>
                            <View className='more'><Iconfont size='26' color='#ccc' name='icon-jiantourukou' /></View>
                          </View>
                        )
                      }):v.type == 4 ? v.items.sku.map(good => {
                        return (
                          <View key={good.goodsId} className='order-goods-items'>
                            <View className='goods-img'>
                              <Image lazyLoad className='pic' src={good.goodsThumbnail} />
                            </View>
                            <View className='goods-info'>
                              <View className='name'>{good.goodsName}</View>
                              {/* <View className='sku'>{good.goodsSkuName}</View> */}
                            </View>
                            <View className='more'><Iconfont size='26' color='#ccc' name='icon-jiantourukou' /></View>
                          </View>
                        )
                      }) : v.type == 2 || v.type == 4 || v.type == 20 ? <View className='order-goods-items'>
                        {/* 方案单 */}
                        {v.items.sku && v.items.sku.length && <View className='goods-info'>{v.items.sku[0].goodsName} {v.items.sku.length > 1 ? '等' : ''}</View>}
                        <View className='more' ><Iconfont size='26' color='#ccc' name='icon-jiantourukou' /></View>
                      </View> : ((v.type !== 1 && v.type !== 5 && v.type !== 13) &&
                        <View className='order-goods-items'>
                          {
                            goods.map((good, idx) => {
                              if (idx > 3) return
                              return (
                                <View key={good.goodsId} className='goods-img'>
                                  <Image lazyLoad className='pic' src={good.goodsThumbnail} />
                                </View>
                              )
                            })
                          }
                          {goods.length < 4 && <View className='goods-info'></View>}
                          <View className='more' style={goods.length > 3 ? 'padding-left: 0' : ''}><Iconfont size='26' color='#ccc' name='icon-jiantourukou' /></View>
                        </View>
                      )
                    }
                    {
                      // 方案单
                      v.type == 2 ||  v.type == 4 && <View className='price-info'>共{programmeNumber}件，金额：<View className='strong'>¥{v.needPayPrice}</View></View>
                    }
                    {hasGoods && <View className='price-info'>共{totalGoodsNumber}件，金额：<View className='strong'>¥{ v.clientSource == 13 ? v.totalPrice : v.needPayPrice}</View></View>}
                    {v.type === 5 && <View className='price-info'>共{totalGoodsNumber}件，金额：<View className='strong'>¥{v.needPayPrice}</View></View>}
                    {v.type === 20 && <View className='price-info'>共{totalGoodsNumber}件，金额：<View className='strong'>¥{v.needPayPrice}</View></View>}
                    {
                      v.action.isCouldApply === 0 && v.apply && v.apply.time > 0 && (
                        <View className='order-status'>
                          <View className='text title'>预约信息</View>
                          <View className='row'>
                            <View className='strong'>预约门店：{v.apply.storeName}</View>
                          </View>
                          <View className='row'>
                            <View className='strong'>预约时间：{dayjs.unix(v.apply.time).format('YYYY.MM.DD HH:mm:ss')}</View>
                          </View>
                        </View>
                      )
                    }
                    {
                      v.type === 5 && (
                        <View className='order-status'>
                          <View className='text'>状态：<View className='em'>{v.insurance.statusLabel}</View></View>
                          <View className='row'>
                            <View className='col'>
                              <View className='text'>车牌：<View className='strong'>{v.insurance.carLicense}</View></View>
                            </View>
                            <View className='col'>
                              <View className='text'>承保单位：<View className='strong'>{v.insurance.supplyCompanyName}</View></View>
                            </View>
                          </View>
                        </View>
                      )
                    }
                    {/* 驾意险 */}
                    {
                      v.type === 13 && (
                        <View className='order-goods-items order-goods-right'>
                          <View className='goods-img'>
                            <Image lazyLoad className='pic' src={v.accidentInsurance.logUrl} mode="aspectFill" />
                          </View>
                          <View className='more'>
                            <View className="c0">￥{v.accidentInsurance.totalPrice}</View>
                            <View className="c6">共1项</View>
                          </View>
                        </View>)
                    }
                    {
                      v.type === 13 && (
                        <View className='order-status'>
                          <View className='text'>投保进度：<View className='em'>{v.accidentInsurance.statusLabel || v.serviceStatusLabel}</View></View>
                          <View className='row'>
                            <View className='col'>
                              <View className='text'>投保车辆：<View className='strong'>{v.accidentInsurance.carLicense}</View></View>
                            </View>
                            <View className='col'>
                              <View className='text'>保险公司：<View className='strong'>{v.accidentInsurance.supplyCompanyName}</View></View>
                            </View>
                          </View>
                        </View>
                      )
                    }
                  </View>
                  {
                    v.type !== 13 && v.type !== 5 && !hasAction && (
                      <View className='order-card-bt'>
                        {v.action.isCouldComment ? <View className='evaluate' onClick={() => {
                          this.setState({
                            isBack: true
                          }, () => {
                            Taro.navigateTo({ url: `/pages/evaluate/index/index?orderNumber=${v.orderNumber}` })
                          })
                        }}>
                          <View className='bubble'>
                            <View className="bubble-text">
                              写评价拿红包
                            </View>
                            <View className="bubble-img">
                              <Image
                                className="img"
                                src={bubbleImg} />
                            </View>
                          </View>
                          <View className='btn'>评价</View>
                        </View> : null}
                        {/* { v.action.isCouldCancel === 1 && <View onClick={() => this.cancelOrder(v.orderNumber)} className='btn border'>取消订单</View> } */}
                        {v.action.isCouldPay === 1 && <View onClick={() => this.toPay(v.orderNumber)} className='btn'>去支付</View>}
                        {v.action.isCouldUpdateApply === 1 && v.apply && <View onClick={() => this.bookingOrder(v, 'edit')} className='btn'>修改预约</View>}
                        {v.action.isCouldApply === 1 && <View onClick={() => this.bookingOrder(v)} className='btn'>去预约</View>}
                      </View>
                    )
                  }
                </View>
              )
            })
          }
          <View className="page-base">已经到底了~</View>
        </View>
      </ScrollView>
    )
  }
}
